﻿using AutoMapper;
using MediatR;
using Medical.Api.Write.Application.Command.Wms.WmsStorageCommand;
using Medical.Domain.Wms;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;
using Medical.Interstructrue;

namespace Medical.Api.Write.Application.Handler.Wms.WmsStorageHandler
{
    /// <summary>
    /// 编辑入库实现
    /// </summary>
    public class UptStorageHandlter : IRequestHandler<UptStorageCommand, ApiResult<int>>
    {
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<UptStorageHandlter> logger;
        /// <summary>
        /// automapper
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 回收登记仓储
        /// </summary>
        private readonly IBaseRepository<WmsStorage> wmsStorageRep;
        /// <summary>
        /// 入库明细仓储
        /// </summary>
        private readonly IBaseRepository<WmsStorageDetail> wmsStorageDetailRep;
        private readonly MedicalDbContext dbContext;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="logger">日志</param>
        /// <param name="mapper">automapper</param>
        /// <param name="wmsStorage">入库仓储</param>
        public UptStorageHandlter(ILogger<UptStorageHandlter> logger, IMapper mapper, IBaseRepository<WmsStorage> wmsStorageRep, IBaseRepository<WmsStorageDetail> wmsStorageDetailRep, MedicalDbContext dbContext)
        {
            this.logger = logger;
            this.mapper = mapper;
            this.wmsStorageRep = wmsStorageRep;
            this.wmsStorageDetailRep = wmsStorageDetailRep;
            this.dbContext = dbContext;
        }

        /// <summary>
        /// 编辑入库和入库明细
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<int>> Handle(UptStorageCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();
            using var transaction = dbContext.Database.BeginTransaction();
            try
            {
                // 1. 获取主表
                var storage = wmsStorageRep.GetModel(request.Id);
                if (storage == null)
                {
                    result.Code = ApiEnums.NotFound;
                    result.Msg = $"未找到Id为{request.Id}的入库记录";
                    result.Data = 0;
                    logger.LogWarning($"编辑失败：未找到Id为{request.Id}的入库记录");
                    return Task.FromResult(result);
                }
                // 2. 更新主表属性
                storage.StorageType = request.StorageType;
                storage.StorageCode = request.StorageCode;
                storage.Warehouse = request.Warehouse;
                storage.Supplier = request.Supplier;
                storage.StorageExplain = request.StorageExplain;
                storage.AuditName = request.AuditName;
                storage.AuditDate = request.AuditDate;
                var updateMain = wmsStorageRep.Update(storage);

                // 3. 删除原有明细
                var oldDetails = wmsStorageDetailRep.GetAll().Where(d => d.StorageId == request.Id && !d.IsDeleted).ToList();
                foreach (var detail in oldDetails)
                {
                    detail.IsDeleted = true;
                }
                if (oldDetails.Count > 0)
                {
                    wmsStorageDetailRep.UpdateRange(oldDetails);
                }

                // 4. 新增新明细
                if (request.StorageDetails != null && request.StorageDetails.Count > 0)
                {
                    var newDetails = request.StorageDetails.Select(dto =>
                    {
                        var entity = mapper.Map<WmsStorageDetail>(dto);
                        entity.StorageId = request.Id;
                        entity.IsDeleted = false;
                        return entity;
                    }).ToList();
                    wmsStorageDetailRep.CreateRange(newDetails);
                }

                transaction.Commit();
                result.Code = ApiEnums.Success;
                result.Msg = "编辑成功";
                result.Data = 1;
                logger.LogInformation($"编辑成功，Id: {request.Id}");
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                result.Code = ApiEnums.Error;
                result.Msg = $"编辑异常: {ex.Message}";
                result.Data = 0;
                logger.LogError(ex, $"编辑异常，Id: {request.Id}");
            }
            return Task.FromResult(result);
        }
    }
}
